package com.lujianfei.redpacketstat.ui.viewmodel

import android.content.Context
import android.content.DialogInterface
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.MutableLiveData
import com.lujianfei.redpacketstat.App
import com.lujianfei.redpacketstat.Constant
import com.lujianfei.redpacketstat.base.BaseViewModel
import com.lujianfei.redpacketstat.database.AppDatabase
import com.lujianfei.redpacketstat.database.bean.RedPacketEntity
import com.lujianfei.redpacketstat.database.bean.UserEntity
import com.lujianfei.redpacketstat.utils.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext


class UserDetailViewModel(private val db: AppDatabase) : BaseViewModel() {
    val uiState = MutableLiveData<UserDetailUiStateEntity>()
    var userEntity: UserEntity? = null
    var redPacketEntity: RedPacketEntity? = null
    fun loadData(userId: Int) {
        launchOnUI {
            withContext(Dispatchers.IO) {
                userEntity = db.userDao().queryById(userId)
                redPacketEntity = db.redpacketDao().queryByUserId(userId)
                if (null == redPacketEntity) {
                    redPacketEntity = RedPacketEntity()
                    redPacketEntity?.userId = userId
                }
                userEntity?.statusString = Utils.getStatusString(userEntity?.status!!)
            }
            emitUi(userEntity = userEntity, redPacketEntity = redPacketEntity)
        }
    }

    private fun emitUi(
        userEntity: UserEntity? = null,
        redPacketEntity: RedPacketEntity? = null,
        showToastString: String? = null,
        showDialog: ShowDialog? = null
    ) {
        uiState.value =
            UserDetailUiStateEntity(userEntity, redPacketEntity, showToastString, showDialog)
    }

    fun save(callback: ((LongArray, LongArray) -> Unit)? = null) {
        launchOnUI {
            val userInsertId = async(Dispatchers.IO) {
                db.userDao().insert(userEntity!!)
            }
            val redPacketInsertId = async(Dispatchers.IO) {
                db.redpacketDao().insert(redPacketEntity!!)
            }
            callback?.let {
                it(userInsertId.await(), redPacketInsertId.await())
            }
        }
    }

    val userNameWatcher: TextWatcher = object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable) {
            super.afterTextChanged(s)
            userEntity?.userName = s.toString()
        }
    }

    val ammountWatcher: TextWatcher = object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable) {
            super.afterTextChanged(s)
            try {
                redPacketEntity?.amount = s.toString().toDouble()
            } catch (e: Exception) {

            }
        }
    }

    fun delete() {
        emitUi(showDialog = ShowDialog("提示", "确定要删除？") {
            launchOnUI {
                val async1 =
                    async(Dispatchers.IO) { db.redpacketDao().delete(redPacketEntity!!) }

                val async2 =
                    async(Dispatchers.IO) { db.userDao().delete(userEntity!!) }

                async1.await()
                async2.await()
                emitUi(showToastString = "已删除")
            }
        })
    }

    fun clickOnProcess(view: View, userEntity: UserEntity) {
        showConfirmDialog(view.context) {
            launchOnUI {
                if (Constant.STATUS_UNPROCESSED == userEntity.status) {
                    userEntity.status = Constant.STATUS_PROCESSED
                } else if (Constant.STATUS_PROCESSED == userEntity.status) {
                    userEntity.status = Constant.STATUS_UNPROCESSED
                }
                val updateResult = async(Dispatchers.IO) { db.userDao().update(userEntity) }
                updateResult.await()
                userEntity.statusString = Utils.getStatusString(userEntity.status)
                emitUi(userEntity = userEntity)
            }
        }
    }

    fun showConfirmDialog(context: Context, callback: () -> Unit) {
        AlertDialog.Builder(context)
            .setTitle("提示")
            .setMessage("确认操作")
            .setPositiveButton("确认") { _: DialogInterface, _: Int ->
                callback()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    fun amountVisibility(): Int {
        return if (App.instance.adminMode) View.VISIBLE else View.GONE
    }
}

data class UserDetailUiStateEntity(
    val userEntity: UserEntity? = null,
    val redPacketEntity: RedPacketEntity? = null,
    val showToastString: String? = null,
    val showDialog: ShowDialog? = null
)


internal abstract class SimpleTextWatcher : TextWatcher {
    override fun beforeTextChanged(
        s: CharSequence,
        start: Int,
        count: Int,
        after: Int
    ) {
    }

    override fun onTextChanged(
        s: CharSequence,
        start: Int,
        before: Int,
        count: Int
    ) {
    }

    override fun afterTextChanged(s: Editable) {}
}